import React from 'react';
import {injectIntl} from 'react-intl';
import axios from 'axios';
import {Card, Form, Row, Select, Col, Button, Tag, Modal, Input} from 'antd';
import {authFun, currentStatus, stubMonitorJSON} from '../../utils/tranStartType';
import {Link} from 'react-router-dom';
import StubPicker from '../../components/pickCity/StubPicker'
import {loadMenus} from "../../redux/menu/menu.redux";
import {connect} from "react-redux";
import LogQueryModal from '../powerStation/logQueryModal';
import EquChargeOrder from '../powerStation/equChargeOrder';
import AuthButton from '../../components/auth/authButton'


const Option = Select.Option;
const FormItem = Form.Item;
const GridItem = Card.Grid;
const createForm = Form.create;

const ItemButton = (props) => {
    return (
        <AuthButton>
        <div style={{textAlign: 'center', padding: 8}} data-auth="002002011">
            <Button style={{width: '80%'}} onClick={props.onClick}>{props.status}</Button>
        </div>
        </AuthButton>
    )
}

@connect(state => state.menu, {loadMenus})
class stubMonitor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            button: [],
            options: [],
            respParams: {
                stubInfo: []
            },
            logQuerySwitch: false,
            equChargeSwitch: false,
            loading: true,
            selectedInfo: {}
        }

    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            values.stubGroupId = values.stubGroupId.currency;
            this.fetchData(values)
        });
    };

    componentWillMount() {
        this.fetchData()
    }

    componentDidUpdate() {
        // authFun(this.state.button, document.querySelectorAll('[data-auth]'));
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            button: nextProps.button
        })
    }

    fetchData = (values) => {
        return axios.get(`/api/monitor/stubGroup/qry`, {params: values, loading: true}).then(res => {
            if (res && res.code == 200) {
                this.setState({
                    respParams: res.data
                })
                if (!values) {
                    this.setState({
                      stubGroupName: res.data.stubGroupId,
                    })
                }
            }
        })
    };
    checkPrice = (rule, value, callback) => {
        const common = this.props.intl.messages.common;
        if (value.currency) {
            callback();
            return;
        }
        callback(common.stubNoEmpty);
    }

    closeEquCharge = () => {
        this.setState({
            equChargeSwitch: false,
        });
    };

    closeLogQuery = () => {
        this.setState({
            logQuerySwitch: false,
        });
    };

    openEquCharge = (item) => {
        console.log(item);
        this.setState({
            equChargeSwitch: true,
            selectedInfo: item
        })
    }

    openLogQuery = (item) => {
        console.log(item);
        this.setState({
            logQuerySwitch: true,
            selectedInfo: item
        })
    };


    render() {
        // authFun(this.state.button, document.querySelectorAll('[data-auth]'));
        const {getFieldDecorator} = this.props.form;
        const gridStyle = {
            width: '25%',
        };
        const common = this.props.intl.messages.common;
        let getIcon = (item) => {
            const status = item.status;
            if (status === '00' || status === '0B') {
                return (
                    <div className="SCard blue">
                        <span>{currentStatus(status)}</span>
                        <span className="stub">
                            <i className="iconfont icon-stubMonitor-copy" onClick={() => {
                                this.openLogQuery(item)
                            }}/>
                            <i className="iconfont icon-order" onClick={() => {
                                this.openEquCharge(item)
                            }} data-auth="002002012"/>
                        </span>
                    </div>
                )
            } else if (status === '01') {
                return (
                    <div className="SCard orange">
                        <span>{currentStatus(status)}</span>
                        <span className="stub">
                            <i className="iconfont icon-stubMonitor-copy" onClick={() => {
                                this.openLogQuery(item)
                            }}/>
                            <i className="iconfont icon-order" onClick={() => {
                                this.openEquCharge(item)
                            }} data-auth="002002012"/>
                        </span>
                    </div>
                )
            } else if (status === '02') {
                return (
                    <div className="SCard red">
                        <span>{currentStatus(status)}</span>
                        <span className="stub">
                            <i className="iconfont icon-stubMonitor-copy" onClick={() => {
                                this.openLogQuery(item)
                            }}/>
                            <i className="iconfont icon-order" onClick={() => {
                                this.openEquCharge(item)
                            }} data-auth="002002012"/>
                        </span>
                    </div>
                )
            } else {
                return (
                    <div className="SCard gray">
                        <span>{currentStatus(status)}</span>
                        <span className="stub">
                            <i className="iconfont icon-stubMonitor-copy" onClick={() => {
                                this.openLogQuery(item)
                            }}/>
                            <i className="iconfont icon-order" onClick={() => {
                                this.openEquCharge(item)
                            }} data-auth="002002012"/>
                        </span>
                    </div>
                )
            }
        };

        let getButton = (item, type) => {
            const status = item.status;
            const stubId = item.stubId;
            const chargeStart = () => {
                if (type != 0) {
                    return
                }
                axios.get('/api/monitor/stub/chargeStart', {params: {stubId}}).then(res => {
                    if (res && res.code == 200) {
                        console.log(res)
                    }
                })
            }
            const chargeEnd = () => {
                if (type != 0) {
                    return
                }
                axios.get('/api/monitor/stub/chargeEnd', {params: {stubId}}).then(res => {
                    if (res && res.code == 200) {
                        console.log(res)
                    }
                })
            }
            if (type != 0) {
                return null;
            }
            if (status === '00') {
                return (
                    <ItemButton {...{status: "未插枪"}}></ItemButton>
                )
            } else if (status === '0B') {
                return (
                    <ItemButton {...{status: "开始充电", onClick: chargeStart}}></ItemButton>
                )
            } else if (status === '01') {
                return (
                    <ItemButton {...{status: "停止充电", onClick: chargeEnd}}></ItemButton>
                )
            } else {
                return null
            }
        };
        return (
            <AuthButton>
                <div>
                    <form form={this.props.form} className="SC-form-tips">
                        <Row gutter={16}>
                            <Col xxl={4} xl={6}>
                                <FormItem
                                >
                                    {getFieldDecorator(`stubGroupId`, {
                                        initialValue: {currency: this.state.stubGroupName}
                                    })(
                                        <StubPicker  useType={true} url="/api/stubGroup/listForOption/qry" mode={true}
                                                    placeholder={'请选择桩群'}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col xxl={3} xl={3}>
                                <FormItem
                                >
                                    {getFieldDecorator(`status`)(
                                        <Select
                                            placeholder={common.status}
                                            allowClear={true}
                                        >
                                            {
                                                stubMonitorJSON.map((item) =>
                                                    <Option value={item.status} key={item.status}>{item.name}</Option>
                                                )
                                            }
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col xxl={3} xl={3}>
                                <FormItem
                                >
                                    {getFieldDecorator(`stubId`)(
                                        <Input placeholder={common.EquipmentNo}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col>
                                <FormItem>
                                    <Button type="primary" className="ant-btn-84"
                                            onClick={this.handleSubmit}>{common.search}</Button>
                                    <Link to="/monitor/monitorPlan">
                                        <Button type="primary" className="ant-btn-84" data-auth={"002002004"}>
                                            {common.charPlan}
                                        </Button>
                                    </Link>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row gutter={24}>
                            <Col className="flex-middle">
                                <span className="statusBlock blue"></span>
                                {common.leisure}:
                                <Tag>{this.state.respParams.free || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock orange"></span>
                                {common.charging}:
                                <Tag>{this.state.respParams.charging || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock red"></span>
                                {common.malfunction}:
                                <Tag>{this.state.respParams.fault || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock gray"></span>
                                {common.off}:
                                <Tag>{this.state.respParams.off || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock gray"></span>
                                {common.plugged}:
                                <Tag>{this.state.respParams.plugged || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock gray"></span>
                                {common.other}:
                                <Tag>{this.state.respParams.other || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock gray"></span>
                                {common.kwLimit}:
                                <Tag>{this.state.respParams.kwLimit || 0}</Tag>
                            </Col>
                            <Col className="flex-middle">
                                <span className="statusBlock gray"></span>
                                {common.kwReal}:
                                <Tag>{this.state.respParams.kwReal || 0}</Tag>
                            </Col>
                        </Row>
                    </form>
                    <div className="stubList">
                        {this.state.respParams.stubInfo.length > 0 ? this.state.respParams.stubInfo.map((item, index) => {
                            return <GridItem className="SC-row" key={item.stubId || index}>
                                {getIcon(item)}
                                <div className="flex-between">
                                    <span>{common.stubID}：</span><span>{item.stubId || `——`}</span></div>
                                <div className="flex-between">
                                    <span>{common.energy}：</span><span>{item.power || `——`}</span></div>
                                <div className="flex-between">
                                    <span>{common.duration}：</span><span>{item.electricTime || `——`}</span>
                                </div>
                                <div className="flex-between">
                                    <span>{common.Current}：</span><span>{item.current || `——`}</span></div>
                                <div className="flex-between">
                                    <span>{common.voltage}：</span><span>{item.voltage || `——`}</span></div>
                                <div className="flex-between"><span>SOC：</span><span>{item.chargeSoc || `——`}</span>
                                </div>
                                <div className="flex-between">
                                    <span>{common.licenseNumber}：</span><span>{item.car || `——`}</span></div>
                                <div className="flex-between"><span>VIN：</span><span>{item.vin || `——`}</span></div>
                                {getButton(item, this.state.respParams.type)}
                            </GridItem>
                        }) : null}
                    </div>
                    <LogQueryModal
                        visible={this.state.logQuerySwitch}
                        onCancel={this.closeLogQuery}
                        selectedInfo={this.state.selectedInfo}
                    />
                    <Modal
                        width="1200px"
                        visible={this.state.equChargeSwitch}
                        title={"充电订单"}
                        onCancel={this.closeEquCharge}
                        footer={[<div key={1} style={{height: 22}}></div>]}
                    >
                        <EquChargeOrder visible={this.state.equChargeSwitch} selectedInfo={this.state.selectedInfo}/>
                    </Modal>
                </div>
            </AuthButton>
        )
    }
}

stubMonitor = createForm()(stubMonitor);
export default injectIntl(stubMonitor);